//
//  HMOAuthViewController.m
//  swift-新浪微博OC版-8-29
//
//  Created by 赵玉忠 on 16/9/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "HMOAuthViewController.h"
#import "UIBarButtonItem+HMBarButtonItem.h"

@interface HMOAuthViewController ()<UIWebViewDelegate>
@property (nonatomic,strong) UIWebView *webView;
@end

@implementation HMOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}
-(void)setupUI{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"新浪微博-登录";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem HMBarButtonItem:nil andWithTitle:@"取消" andWithTarget:self andWithAction:@selector(close)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem HMBarButtonItem:nil andWithTitle:@"自动填充" andWithTarget:self andWithAction:@selector(autoFill)];

    
    [self.view addSubview:self.webView];
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",WB_APPKEY,WB_REDIRECT_URI];
    
    // 加载指定的登录页面
    // 1. 初始化一个url
    NSURL *url = [NSURL URLWithString:urlString];
    // 2. 通过url初始化一个请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 3. 加载该请求
    [_webView loadRequest:request];
}
-(void)close{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)autoFill{
    NSString *js = @"document.getElementById('userId').value = '18301166921';document.getElementById('passwd').value = '18301166921';";
    [_webView stringByEvaluatingJavaScriptFromString:js];
}
#pragma mark - 懒加载webView
-(UIWebView *)webView{
    if (_webView == nil) {
        _webView = [[UIWebView alloc]init];
    }
    return _webView;
}

#pragma mark - UIWebViewDelegate
// 开始加载的时候
-(void)webViewDidStartLoad:(UIWebView *)webView{
    [SVProgressHUD show];
}
// 结束加载的时候
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    [SVProgressHUD dismiss];
}
// 加载失败的时候
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [SVProgressHUD dismiss];
}

@end
